package red.internal.core.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import red.internal.core.message.Direction;
import red.internal.core.message.HeartbeatMessage;

/**
 * @author Jin Zheng
 * @since 2019-05-02
 */
public class HeartbeatHandler extends SimpleChannelInboundHandler<HeartbeatMessage>
{
	private static Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

	public HeartbeatHandler()
	{
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HeartbeatMessage request) throws Exception
	{
		if (request.getDirection() == Direction.RECEIVE)
			return;

		HeartbeatMessage response = request.success();
		ctx.writeAndFlush(response);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
	{
		if (evt instanceof IdleStateEvent)
		{
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE)
			{
				if (logger.isDebugEnabled())
				{
					logger.warn("Read idle, no receive PONG, close!");
				}
				ctx.close();
			}
			else if (event.state() == IdleState.WRITER_IDLE)
			{
				HeartbeatMessage request = HeartbeatMessage.create();
				ctx.writeAndFlush(request);
			}
		}

		super.userEventTriggered(ctx, evt);
	}

}
